package com.example.elysiumease;

import com.example.elysiumease.mapper.SoulSinMapper;
import com.example.elysiumease.model.Sin;
import com.example.elysiumease.model.Soul;
import com.example.elysiumease.model.SoulSin;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@Transactional
@Commit
public class SoulSinMapperTest {

    @Autowired
    private SoulSinMapper soulSinMapper;

    private SoulSin createTestSoulSin() {
        SoulSin soulSin = new SoulSin();

        // 初始化并设置Soul对象
        Soul soul = new Soul();
        soul.setSoulId(16); // 假设已存在该ID的记录
        soulSin.setSoul(soul);

        // 初始化并设置Sin对象
        Sin sin = new Sin();
        sin.setSinId((short)2); // 假设已存在该ID的记录
        soulSin.setSin(sin);

        soulSin.setOccurrenceCount((short)3);
        return soulSin;
    }

    @Test
    void testInsertAndSelect() {
        SoulSin soulSin = createTestSoulSin();

        // 插入记录
        int insertResult = soulSinMapper.insert(soulSin);
        assertEquals(1, insertResult);

        // 查询验证
        SoulSin dbSoulSin = soulSinMapper.selectByCompositeKey(
                soulSin.getSoul().getSoulId(),
                soulSin.getSin().getSinId()
        );
        assertNotNull(dbSoulSin);
        assertEquals(3, Optional.ofNullable(dbSoulSin.getOccurrenceCount()));
    }

    @Test
    void testUpdateOccurrence() {
        SoulSin soulSin = createTestSoulSin();

//        soulSinMapper.insert(soulSin);

        // 更新次数
        soulSin.setOccurrenceCount((short) 5);
        int updateResult = soulSinMapper.updateOccurrence(soulSin);
        assertEquals(1, updateResult);

        // 验证更新
//        SoulSin updated = soulSinMapper.selectByCompositeKey(
//                soulSin.getSoul().getSoulId(),
//                soulSin.getSin().getSinId()
//        );
//        assertEquals(5, Optional.ofNullable(updated.getOccurrenceCount()));
    }

    @Test
    void testDelete() {
        SoulSin soulSin = createTestSoulSin();
//        soulSinMapper.insert(soulSin);

        // 删除记录
        int deleteResult = soulSinMapper.deleteByCompositeKey(soulSin);
        assertEquals(1, deleteResult);

        // 验证删除
//        SoulSin deleted = soulSinMapper.selectByCompositeKey(
//                soulSin.getSoul().getSoulId(),
//                soulSin.getSin().getSinId()
//        );
//        assertNull(deleted);
    }

    @Test
    void testSelectBySoulId() {
        SoulSin soulSin = createTestSoulSin();
//        soulSinMapper.insert(soulSin);

        List<SoulSin> list = soulSinMapper.selectBySoulId(16);
        assertFalse(list.isEmpty());
        assertEquals(1, list.size());
    }
}